package com.nifostasky.shrio.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nifostasky.common.utils.JWTUtil;
import com.nifostasky.common.utils.R;
import com.nifostasky.entity.SysUser;
import com.nifostasky.service.SysUserService;
import com.nifostasky.shrio.form.SysLoginForm;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 登录方法
 */
@RestController
@RequestMapping("/login")
@AllArgsConstructor
public class LoginController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     */
    @SneakyThrows
    @PostMapping("/login")
    public R login(@RequestBody SysLoginForm form){
        //用户信息
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getUsername,form.getUsername())
        );

        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }

        Map<String,Object> claims = new HashMap<>();
        String json = JSON.toJSONString(user);
        //生成token
        String jwt = JWTUtil.createJWT(UUID.randomUUID().toString(), json, user.getUsername(), 1000 * 60 * 30L, claims);
        Map<String,Object> results = new HashMap<>();
        results.put("token",jwt);
        return R.ok(results);
    }

    /**
     * 注册用户
     */
    @PostMapping("/register")
    public R register(@RequestBody SysUser user){
        String salt = UUID.randomUUID().toString().replace(".", "").substring(0,20);
        String password = new Sha256Hash(user.getPassword(), salt).toHex();
        user.setSalt(salt);
        user.setPassword(password);
        user.setStatus(1);
        user.setCreateTime(new Date());
        sysUserService.save(user);
        return R.ok();
    }
}
